# @Time  :2021/5/27 21:25
# @Author: Houtaroy
from dataclasses import dataclass
from typing import List

from flask_koala.system.models import UserDTO, PermissionDTO
from flask_koala.system.utils import TreeUtil


@dataclass
class UserAuthority(UserDTO):
    permissions: List[str] = None
    authorities: List[str] = None

    def __init__(self):
        print(self.roles)

    def post_init(self):
        """
        追加初始化, 根据用户角色生成权限代码列表和接口代码列表
        """
        if self.roles is not None and len(self.roles) > 0:
            permissions = self.__init_permissions()
            self.__init_permission_codes(permissions)
            self.__init_authorities(permissions)
        self.roles = []

    def __init_permissions(self):
        result = []
        if self.roles is None or len(self.roles) <= 0:
            return result
        for role in self.roles:
            result.extend(role.permissions)
        return TreeUtil.expand(result)

    def __init_permission_codes(self, permissions: List[PermissionDTO]):
        self.permissions = [permission.code for permission in permissions]

    def __init_authorities(self, permissions: List[PermissionDTO]):
        result = []
        for permission in permissions:
            result.extend([api.code for api in permission.apis])
        self.authorities = list(set(result))
